<!-- organization management -->
<script setup lang="ts">
import { reactive, ref, toRefs, onMounted, watch } from 'vue';
import { ElPagination, ElMessageBox, ElMessage } from "element-plus"
import { Page } from '@vben/common-ui';
import { $t } from '#/locales/index.js'
import { trimStringParams } from '#/utils/trimStringParams'
import { getSysOrgTreeApi, updateStatusApi } from '#/api/system/systemOrg';
import subOrgIcon from '#/assets/images/sub-add.png';

import { Query, EditOrgDialog } from './modules/systemOrg'
import { Pencil, Ban, SquarePlay } from '@vben/icons';

const editOrgDialogRef = ref<InstanceType<typeof EditOrgDialog> | null>(null)

const tableLoading = reactive([0, 0]);
const loading = ref(false)
const total = ref(0)
const defaultQueryData = {
  name: '',
  status: null
}
const queryData = reactive({ ...defaultQueryData });
const tableData = ref<any>([]);
const pageData = reactive({
  curPage: 1,
  pageSize: 10,
});

const getTabelData = () => {
  const { curPage, pageSize } = toRefs(pageData)
  const params = {
    curPage: curPage.value,
    pageSize: pageSize.value
  } as any;
  const trimData = trimStringParams(queryData)
  Object.keys(trimData).forEach(key => {
    const kVal = trimData[key as keyof typeof trimData]
    if (kVal && key !== 'status' || key === 'status' && kVal !== null) {
      params[key] = kVal
    }
  })
  tableLoading[0] = 1
  getSysOrgTreeApi(params)
    .then((res) => {
      const { data, pageInfo } = res;
      tableData.value = data;
      total.value = pageInfo?.totalRows
    })
    .finally(() => {
      tableLoading[0] = 0;
    });
};

const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  getTabelData()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  getTabelData()
}
const resetQuery = () => {
  Object.assign(queryData, defaultQueryData)
  getTabelData()
}

const addOrg = (data?: any) => {
  editOrgDialogRef.value?.inint(!!data? 'SUBLEVEL' : 'PLEVEL', data)
}

const setStatus = (data: any) => {
  ElMessageBox.confirm(
    $t('common.submitTxt', [$t('common.updateTxt', [$t('orgMgr.orgStatusTxt')])]),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      tableLoading[0] = 1
      updateStatusApi({ id: data.id, status: data.status === 'enable' ? 'disable' : 'enable' }).then(() => {
        ElMessage.success($t('common.updateTxt', [$t('common.successTxt')]))
        getTabelData()
      }).finally(() => {
        tableLoading[0] = 0
      })
    })
    .catch(() => { })
}

const editOrg = (data: any) => {
  const editData = {
    ...data
  }
  editOrgDialogRef.value?.inint('EDIT', editData)
}
watch(
  () => tableLoading,
  (val) => {
    if (val) {
      const isLoading = val.some(i => i === 1)
      loading.value = isLoading
    }
  },
  { deep: true },
)

onMounted(() => {
  getTabelData();
})

</script>
<template>
  <Page class="h-full">
    <section class="flex h-full flex-col bg-[#fff] p-[24px] rounded-lg">
      <Query v-model="queryData" class="mb-[5px]" @query-data="getTabelData" @reset-query="resetQuery" />
      <div class="mb-[16px]">
        <el-button type="primary" @click="addOrg(null)">
          {{ $t('common.newTxt') }}
        </el-button>
      </div>
      <el-table :tree-props="{ checkStrictly: false }" row-key="id" :data="tableData" v-loading="loading" height="100%">
        <el-table-column prop="name" :label="$t('orgMgr.orgNameTxt')" min-width="200">
          <template #default="{ row }">
            <span>{{ row.name ?? '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('orgMgr.orgStatusTxt')" min-width="80">
          <template #default="{ row }">
            <span class="inline-block w-[10px] h-[10px] rounded-[5px]"
              :style="{ background: row.status == 'enable' ? '#30A46C' : '#AEAEAE' }"></span>
            <span class="ml-[8px]">{{row.status == 'enable' ? $t('common.activeTxt') : $t('common.inactiveTxt') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('common.createTimeTxt')" min-width="100">
          <template #default="{ row }">
            <div>{{ row.createTime }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.handleTxt')" min-width="80">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-tooltip effect="dark" :content="$t('common.newTxt', [$t('orgMgr.subOrgTxt')]) " :show-after="1000" placement="top">
                <el-button link @click="addOrg(row)">
                  <el-icon :style="{ backgroundImage: `url(${subOrgIcon})`, backgroundSize: '100% 100%', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }"></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark"
                :content="row.status === 'enable' ? $t('common.fiddenTxt') : $t('common.useTxt')"
                :show-after="1000" placement="top">
                <el-button :icon="row.status === 'enable' ? Ban : SquarePlay" link @click="setStatus(row)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" :content="$t('common.editTxt')" :show-after="1000" placement="top">
                <el-button :icon="Pencil" link @click="editOrg(row)"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <ElPagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
        size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.pageSize" :total="total"></ElPagination>
    </section>
    <EditOrgDialog ref="editOrgDialogRef" @queryTable="getTabelData"></EditOrgDialog>
  </Page>
</template>
<style lang="less" scoped>
</style>
